package com.liu.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

/**
 *
 * @author liubo
 */
public class ParseByDom1 {
	private String xmlPath = "";

	public ParseByDom1(String xmlPath){
		this.xmlPath = xmlPath;
	}

	public void read() {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();
			// 解析XML文件，构建相应的DOM树
			Document dom = db.parse(xmlPath);
			// 获取DOM树的根节点
			Element element = dom.getDocumentElement();
			// 获取DOM树的根节点下的所有节点
			NodeList nodeList = element.getChildNodes();
			//NodeList nodeList = element.getElementsByTagName("RootNode");
			// 遍历所有brand
			for (int i = 0; i < nodeList.getLength(); i++) {
				Node node = nodeList.item(i);
				String nodeName = node.getNodeName();
				String nodeValue = node.getNodeValue();
				System.out.println(nodeName+":"+nodeValue);
//				if (node.getNodeType() == Node.ELEMENT_NODE) {
//					String name = node.getNodeName();
//					String nodeName = node.getNodeName();
//					String nodeValue = node.getNodeValue();
//					System.out.println(nodeName+":"+nodeValue);
//				}
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}